/**
 * @class NG.views.FADList
 * @extends NG.util.List
 * 
 * This panel is used for listing FADs.
 * This component is registered as 'netgis-FADList' name.
 */
NG.views.FADList = Ext.extend(NG.util.List, {
	deferEmptyText:true,
	
	/**
	 * Default value is 'FAD Bulunamadı'.
	 * @type String
	 */
	emptyText: 'FAD Bulunamadı',
	loadingText: 'FAD Yükleniyor',	
	scroll: 'vertical',
	singleSelect: true,
	minHeight: 300,
	height: 300,
	width: 500,
	
	/**
	 * Which map is invoked this list.
	 * @type NG.views.MapView
	 */
    mapView: null,
    
    /**
     * Which workspace's fads are listed.
     * @type NG.models.Workspace
     */
    workspace:null,
    
    initComponent: function(){
    	var ws = this.workspace;
        this.itemTpl = new Ext.XTemplate(
            '<tpl if="visibility == true">', 
                '<img width="16" src="img/check-round-green.png">', 
            '</tpl>', 
            '<tpl if="visibility == false">', 
                '<img width="16" src="img/check-round-grey.png">', 
            '</tpl>', 
            '&nbsp;<img width="16" src="' + ws.getIconUrl() + '{iconType}">', 
            '<span class="gx-layer-item">{tableDisplayName}</span>'
        );

        NG.views.FADList.superclass.initComponent.call(this);
    },

    /**
     * List is consists of NG.model.Table objects.
     * @param {NG.util.List} list Fad list
     */
    loadFAD: function (list){
    	if (list.store && list.store.getCount() > 0)
    		return;
    	list.el.mask(L_LOADING);
    	
    	function loadFAD (fadList){
    		list.store.loadData(fadList);
			list.applyButton.enable();
			list.el.unmask();
    	}
    	
    	function doNCDDServices (ncddServicesCommand, sessionID){
			if (NGFADCache.containsKey(ncddServicesCommand.getCacheKey())) {
				var fadList = NGFADCache.get(ncddServicesCommand.getCacheKey());
				loadFAD(fadList);
			} else {
	    		NGServiceRequester.executeCommand(ncddServicesCommand, sessionID, {
	            	requestFinished: function (response) {
	            		NGLogger.info("FADList loadFAD requestFinish");
	            		var ncddServicesResponse = new NG.response.NCDDServices({
	            			xmlData: response
	            		});
	            		list.store.removeAll();
	            		var fadList = ncddServicesResponse.getResultList();
	            		loadFAD (fadList);
						//Add into NGFADCache
	            		NGFADCache.add(ncddServicesCommand.getCacheKey(), fadList);
	            	},
	            	requestFail: function (response) {
						list.store.add({
							catName: 'İstek Başarısız'
						});
						list.applyButton.disable();
						list.el.unmask();	            		
	            	}
	    		});			
			}    		
    	}
    	
		var ncddServicesCommand = new NG.command.NCDDServices({
			workspaceName: this.workspace.getName(),
        	runXmlUrl: this.workspace.getRunXmlUrl()
		});		    	
		
    	var ws = this.workspace;
		var session = NGServiceRequester.isAlreadyLoggedIn(ws.getUsername(), ws.getLoginUrl());
		if (session) {
			doNCDDServices(ncddServicesCommand, session.sessionID);
		} else {
			NGServiceRequester.login(ws.getUsername(), ws.getPassword(), ws.getLoginUrl(), {
				loginSuccess: function(sessionID) {
					doNCDDServices(ncddServicesCommand, sessionID);
				},
				loginFail: function(response) {
					list.store.add({
						catName: 'Bağlantı sağlanamadı'
					});
					list.applyButton.disable();
					list.el.unmask();
				}
			});
		}	
    },
    
    /**
     * Only one FAD can be selected. So that, this method returns list contains of at most one element.
     * 
     * @param {Boolean} selected if true selected fads else unselected fads
     * @return {String} selected FADs' id separated by ";". If there is no selected row an empty string is returned.
     */
    getSelectedFADs: function (selected){
    	selected = Ext.isEmpty(selected) ? true : selected;
    	var result = "";
    	for ( var i = 0; i < this.getStore().getCount(); i++) {
            var record = this.getStore().getAt(i);
            if (selected ? record.get("visibility") : !record.get("visibility"))
            	result += record.getCatID() + ";";
		}
    	return result.removeLastChar();
    },
    
    /**
     * 
     * @return {String} Selected fads' id separated by ;
     */
    getSelectedFADList: function (){
    	return this.getSelectedCategories(true);
    },
    
    /**
     * Make all records as unselected.
     */
    clearSelections: function (){
    	for ( var i = 0; i < this.getStore().getCount(); i++) {
    		var tmpRecord = this.getStore().getAt(i); 
    		tmpRecord.set("visibility", false);					
		}    	
    },
    
    listeners: {
        itemtap: function(dataview, index, item, e){
        	//Make all rows unselected
        	var record = dataview.getStore().getAt(index); 
        	for ( var i = 0; i < dataview.getStore().getCount(); i++) {
        		var tmpRecord = dataview.getStore().getAt(i); 
        		if (record.equalsTo(tmpRecord))
        			continue;
        		tmpRecord.set("visibility", false);					
			}
            record.set("visibility", !record.get("visibility"));
            
            if (record.get("visibility") === true) {
            	dataview.mapView.setSelectedFAD(record);            	
            } else {
            	dataview.mapView.setSelectedFAD(null);
            }
        },    	
    	afterrender : function (dataview) {
    		this.loadFAD(dataview);
    	} 
    }
    
});

/**
 * Creates an overlay panel for listing fads.
 * 
 * @param {Object} config Includes mapView, workspace
 * @return {Ext.Panel} fad list panel
 */
NG.views.FADListOverlay = function (config) {
	config = config || {};
	var applyButton = new Ext.Button({
		ui: 'confirm',
		text: L_APPLY,
		disabled: true,
		handler: function(){
			var selectedFADList = Ext.getCmp('netgis-FADList-id').getSelectedFADList();
			overlay.hide();
			//render map with new categories
			//config.mapView.renderWorkspaceWithOffCategories(unSelectedCategories);
		}
	});
	
    var overlay = new Ext.Panel({
		fullscreen: Ext.is.Phone,
	    floating: true,
	    modal: true,
	    centered: true,
	    width: Ext.is.Phone ? 260 : 400,
	    //height: Ext.is.Phone ? 220 : 400,
	    scroll: 'vertical',
    	dockedItems: [{
			//dock : 'bottom',
			xtype: 'toolbar',
			ui   : 'light',
	    	title: L_FADs,
			items: [{
					iconCls: 'delete',
					iconMask: true,
					ui: 'plain',
					handler: function (){
						overlay.hide();
					}
				}
				,{xtype:'spacer'}
				,{
					iconCls: 'trash',
					iconMask: true,
					ui: 'plain',
					handler: function (){
						var fadList = Ext.getCmp('netgis-FADList-id');
						fadList.clearSelections();
					}
				}
				//,applyButton
			]
    	}],  //!dockedItems          	
        items: [{
        	id: 'netgis-FADList-id',
        	xtype: 'netgis-FADList',
        	applyButton: applyButton, 
        	workspace: config.workspace,
        	mapView: config.mapView,
        	store: new Ext.data.Store({
        	    model: 'NG.models.Table',
        	    data : []
        	})
        }]
    });
	
	return overlay;
};

/**
 * @ignore
 */
Ext.reg('netgis-FADList', NG.views.FADList);
